package routes

import (
	"com.yt/config"
	v1 "com.yt/routes/api/v1"
	"com.yt/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/iGoogle-ink/gopay"
	"github.com/iGoogle-ink/gopay/pkg/util"
	"github.com/iGoogle-ink/gopay/wechat"
	"log"
	"net/http"
)

func SetRoute(app *gin.Engine) {
	apiv1 := app.Group("api/v1")
	{
		//获取商品列表
		apiv1.GET("products", v1.GetListProductList)
		//商品详情
		apiv1.GET("products/query", v1.GetProductById)
		//订单 下单
		apiv1.POST("orders", v1.GenerateOrder)
		//订单 查询订单
		apiv1.GET("orders/query", v1.GetOrderByOrderSn)
		//发起支付请求
		apiv1.POST("orders/pay", v1.PayOrder)
	}
	//支付回调 todo
	app.GET("wx/paytest", func(ctx *gin.Context) {
		client := wechat.NewClient(config.AppConfig.AppId, config.AppConfig.MchId, config.AppConfig.AppKey, true)
		// 打开Debug开关，输出请求日志，默认关闭
		client.DebugSwitch = gopay.DebugOn

		// 设置国家：不设置默认 中国国内
		//    wechat.China：中国国内
		//    wechat.China2：中国国内备用
		//    wechat.SoutheastAsia：东南亚
		//    wechat.Other：其他国家
		client.SetCountry(wechat.China)
		// 初始化 BodyMap
		bm := make(gopay.BodyMap)
		bm.Set("nonce_str", util.GetRandomString(32)).
			Set("body", "H5支付").
			Set("out_trade_no", utils.GenerateOrderSn()).
			Set("total_fee", 1).
			Set("spbill_create_ip", "127.0.0.1").
			Set("notify_url", "http://www.itcast.cn").
			Set("trade_type", wechat.TradeType_H5).
			Set("device_info", "WEB").
			Set("sign_type", wechat.SignType_MD5).
			//Set("referer", ctx.Request.Referer()).
			SetBodyMap("scene_info", func(bm gopay.BodyMap) {
				bm.SetBodyMap("h5_info", func(bm gopay.BodyMap) {
					bm.Set("type", "Wap")
					bm.Set("wap_url", "http://www.itcast.cn")
					bm.Set("wap_name", "H5测试支付")
				})
			})

		// 参数 sign ，可单独生成赋值到BodyMap中；也可不传sign参数，client内部会自动获取
		// 如需单独赋值 sign 参数，需通过下面方法，最后获取sign值并在最后赋值此参数
		sign := wechat.GetParamSign(config.AppConfig.AppId, config.AppConfig.MchId, config.AppConfig.AppKey, bm)
		// sign, _ := wechat.GetSanBoxParamSign("wxdaa2ab9ef87b5497", mchId, apiKey, body)
		bm.Set("sign", sign)
		wxRsp, err := client.UnifiedOrder(bm)
		if err != nil {
			utils.NewErrorMsg(ctx, err.Error())
			return
		}
		if wxRsp.ResultCode != "SUCCESS" {
			fmt.Println(wxRsp.ReturnMsg)
		}
		log.Println(wxRsp)
		ctx.Header("Referer", ctx.Request.Referer())
		ctx.Redirect(http.StatusFound, wxRsp.MwebUrl)
		return
	})
}
